# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 聚合管道操作之merge用法2.py
# @Author: dongguangwen
# @Date  : 2025-06-15 18:22
from datetime import datetime
from pymongo import MongoClient

# 连接到主数据库 learning_mongodb
client = MongoClient("mongodb://root:root123@192.168.1.119:27017/")

# 主数据所在的数据库和集合
main_db = client["learning_mongodb"]
users_collection = main_db["users"]

# 可选：插入测试数据
test_users = [
    {"name": "Alice", "address": {"city": "Shanghai"}, "is_active": True},
    {"name": "Bob", "address": {"city": "Beijing"}, "is_active": True},
    {"name": "Charlie", "address": {"city": "Shanghai"}, "is_active": False},
    {"name": "David", "address": {"city": "Guangzhou"}, "is_active": True},
    {"name": "Eve", "address": {"city": "Beijing"}, "is_active": True},
]
users_collection.insert_many(test_users)
print("✅ 已插入测试用户数据")


pipeline = [
    # 1️⃣ 筛选活跃用户
    {"$match": {"is_active": True}},

    # 2️⃣ 按城市分组统计数量
    {
        "$group": {
            "_id": "$address.city",
            "user_count": {"$sum": 1}
        }
    },

    # 3️⃣ 使用 $merge 写入到另一个数据库 analytics_db 的 user_stats 集合
    {
        "$merge": {
            "into": {
                "db": "analytics_db",   # 目标数据库名
                "coll": "user_stats"    # 目标集合名
            },
            "on": "_id",                # 匹配字段
            "whenMatched": "replace",   # 如果匹配则替换整个文档
            "whenNotMatched": "insert"  # 如果不匹配则插入新文档
        }
    }
]

# 执行聚合
result = list(users_collection.aggregate(pipeline))
print(result)
print("✅ 聚合结果已写入 analytics_db.user_stats")

# 连接到目标数据库
analytics_db = client["analytics_db"]
result_collection = analytics_db["user_stats"]

# 输出写入的结果
print("\n📊 写入到 analytics_db.user_stats 的结果：")
for doc in result_collection.find():
    print(doc)

"""
✅ 已插入测试用户数据
[]
✅ 聚合结果已写入 analytics_db.user_stats

📊 写入到 analytics_db.user_stats 的结果：
{'_id': 'Shanghai', 'user_count': 1}
{'_id': 'Guangzhou', 'user_count': 1}
{'_id': 'Beijing', 'user_count': 2}
"""